//
//  Util.swift
//  SwiftBase
//
//  Created by 郭艳波 on 2018/3/7.
//  Copyright © 2018年 郭艳波. All rights reserved.
//

import Foundation
import UIKit

class CoreUtil {
    public static let sharedInstance = CoreUtil()
    private init() {}
    
    // 数组转json
    public static func arrayToJson(from object: Any) -> String? {
        if let objectData = try? JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions(rawValue: 0)) {
            let json = String(data: objectData, encoding: .utf8)
            return json
        }
        return nil
    }

    // 字典转json
    public static func dictToJson(dictionary: NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            return ""
        }

        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)

        return JSONString! as String
    }
    
    // json转字典
    public static func jsonToDict(jsonString:String) -> NSDictionary{
        let jsonData:Data = jsonString.data(using: .utf8)!

        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }

        return NSDictionary()
    }
    
    // 当前时间的时间戳
    public static func currentInterval() -> Int {
        let now = NSDate()
        
        let timeInterval: TimeInterval = now.timeIntervalSince1970
        return Int(timeInterval)
    }

    // 时间戳转时间
    public static func timeStampToString(timeStamp:Int) -> String {

        let string = NSString(string: "\(timeStamp)")

        let timeStamp:TimeInterval = string.doubleValue
        let datefmatter = DateFormatter()
        datefmatter.dateFormat="yyyy-MM-dd"

        let date = NSDate(timeIntervalSince1970: timeStamp) as Date

        return datefmatter.string(from: date)
    }
    
    // 时间戳转时间
    public static func timeStampToDate(timeStamp:Int64) -> Date {
        let timeInterval:TimeInterval = TimeInterval(timeStamp)
        return Date(timeIntervalSince1970: timeInterval)
    }
    
    // 时间戳转小时分钟
    public static func timeStampToHourMinute(timeStamp:String) -> String {
        let string = NSString(string: timeStamp)
        
        let timeStamp:TimeInterval = string.doubleValue
        let datefmatter = DateFormatter()
        datefmatter.dateFormat="hh:mm"
        
        let date = NSDate(timeIntervalSince1970: timeStamp) as Date
        
        return datefmatter.string(from: date)
    }
    
    // 时间戳返回上午下午
    public static func timeStampGetAmOrPm(timeStamp:String) -> String {
        
        let string = NSString(string: timeStamp)
        let timeStamp:TimeInterval = string.doubleValue
        let date = NSDate(timeIntervalSince1970: timeStamp) as Date
        
        let calendar = Calendar.current
        let hour = calendar.component(.hour, from: date)
        
        if (hour > 12) {
            return "PM"
        } else {
            return "AM"
        }
    }
    
    //判断是不是手机号
    public static func isPhoneNumber(phoneNumber: String)->Bool {
        if phoneNumber.count == 0 {
            return false
        }
        
        let CM = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"
        let CU = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"
        let CT = "^((133)|(153)|(17[3,7])|(18[0,1,9]))\\d{8}$"
        
        let regextestcm = NSPredicate(format: "SELF MATCHES %@", CM)
        let regextestcu = NSPredicate(format: "SELF MATCHES %@", CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@", CT)
        
        if ((regextestcm.evaluate(with: phoneNumber)  == true)
            || (regextestct.evaluate(with: phoneNumber) == true)
            || (regextestcu.evaluate(with: phoneNumber) == true)) {
            return true
        } else {
            return false
        }
    }
    
    //判断是不是邮箱
    public static func isEmail(email: String)->Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
        
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: email)
    }
    
    //压缩图片
    public static func zipImage(image: UIImage, scale: CGFloat, percent: CGFloat) -> Data {
        //压缩图片尺寸
        UIGraphicsBeginImageContext(CGSize(width: image.size.width*scale, height: image.size.height*scale))
        image.draw(in: CGRect(x: 0, y: 0, width: image.size.width*scale, height:image.size.height*scale))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        //高保真压缩图片质量
        return UIImageJPEGRepresentation(newImage, percent)!
    }
}
